﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Collections.Generic;
using Chi.Lib.DBHelper;



public partial class ShowAllTableSchema : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        Database db = DBHelperSMO.GetDBInstance();
        foreach (Microsoft.SqlServer.Management.Smo.Table tb in db.Tables)
        {
            Label lb = new Label();
            lb.ID = "lb_" + tb.ID.ToString();
            lb.Text = "<br><br><h2>" + tb.Name + "</h2>";

            GridView gv = new GridView();
            gv.ID = tb.Name;
            gv.AutoGenerateColumns = false;
            gv.HeaderStyle.BackColor = gvView.HeaderStyle.BackColor;
            foreach (DataControlField dcf in gvView.Columns)
            {
                gv.Columns.Add(dcf);
            }
            gv.DataSource = GetTableColumns(tb);
            gv.DataBind();

            PlaceHolder1.Controls.Add(lb);
            PlaceHolder1.Controls.Add(gv);
        }

    }

    public List<DBHelperTableSchema> GetTableColumns(Microsoft.SqlServer.Management.Smo.Table table)
    {
        //DBHelperTableSchema

        List<DBHelperTableSchema> SchemaLst = new List<DBHelperTableSchema>();
        int i = 1;
        foreach (Column col in table.Columns)
        {
            DBHelperTableSchema colSchema = new DBHelperTableSchema();
            colSchema.SEQ = i.ToString();
            colSchema.PK = col.InPrimaryKey ? "*" : "";
            colSchema.ColumnName = col.Name;
            colSchema.DataType = col.DataType.Name;
            colSchema.MaximunLength = col.DataType.MaximumLength.ToString();
            colSchema.NullAble = col.Nullable ? "Null" : "";
            colSchema.Default = col.Default;
            colSchema.Descriptions = col.ExtendedProperties.Contains("MS_Description") ?
                                    col.ExtendedProperties["MS_Description"].Value.ToString() : "";

            SchemaLst.Add(colSchema);
            i++;
        }

        return SchemaLst;
    }
}
